import {getStorageSync, setStorage} from "../utils/Storage";
import Wx from "../utils/Wx";
import CustomError from "../utils/CustomError";

module.exports = {
    /*
    * 获取用户信息
    * */
    getUserInfo: async function () {
        try {
            let storageUserInfo = getStorageSync("userInfo");
            if (storageUserInfo && storageUserInfo.openId) {
                return storageUserInfo;
            } else {
                let res = await Wx.cloudFunction("user", {actionName: "getUserInfo"});
                setStorage("userInfo", res);
                return res
            }
        } catch (e) {
            throw new CustomError(e, "User.getUserInfo").parse()
        }
    },

    /*
    * 获取微信绑定手机号
    * */
    getPhoneNumber: async function (cloudID) {
        try {
            let res = await Wx.cloudFunction("user", {
                actionName: "getPhoneNumber",
                cloudID: cloudID
            })
            setStorage("userInfo.phone", res.phoneNumber);
            return res.phoneNumber
        } catch (e) {
            throw new CustomError(e, "User.getPhoneNumber").parse()
        }
    },

    /*
    * 更新用户信息
    * */
    updateUsrInfo: async function (data = {}) {
        try {
            let res = await Wx.cloudFunction("user", Object.assign(
                {actionName: "updateUsrInfo"},
                data
            ));
            setStorage("userInfo", res);
            return res
        } catch (e) {
            throw new CustomError(e, "User.updateUsrInfo").parse()
        }
    },

    /*
    * 增加浏览记录
    * */
    addBrowsingRecords: function (data = {}) {
        try {
            return Wx.cloudFunction("user", {
                actionName: "addBrowsingRecords",
                rid: data.rid,
                sharerId: data.sharerId
            });
        } catch (e) {
            throw new CustomError(e, "User.addBrowsingRecords").parse()
        }
    },

    /*
    * 获取助力值
    * */
    getHelperCount: function () {
        try {
            return Wx.cloudFunction("user", {actionName: "getHelperCount"});
        } catch (e) {
            throw new CustomError(e, "User.getHelperCount").parse()
        }
    },

    /*
    * 用户反馈
    * */
    addFeedback: async function (data = {}) {
        try {
            return await Wx.cloudFunction("user", Object.assign(
                {actionName: "addFeedback"},
                data
            ));
        } catch (e) {
            throw new CustomError(e, "User.addFeedback").parse()
        }
    },

}